/* **************************************************************************
 *
 * Copyright 2007-2010 Jeff Hardy
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * *************************************************************************/

using System.Threading;
using System.Web;
using System.Web.SessionState;
using NWSGI.AspNet;

namespace NWSGI
{
    /// <summary>
    /// An HttpHandler that implements the Python WSGI specification. The handler ues IronPython to launch
    /// the WSGI applications, so it will likely not be 100% compatible with all Python web aplications.
    /// </summary>
    /// <example>
    /// To use this HttpHandler, put this file and copies of IronPython.dll, IronPython.Modules.dll,
    /// Microsoft.Scripting.dll, and Microsoft.Scripting.Core.dll in the web applications bin directory
    /// and use the following web.config:
    /// <configuration>
    ///   <system.webServer>
    ///     <handlers>
    ///       <add name="WsgiHandler" path="*.wsgi" verb="*" type="NWSGI.WsgiHandler" resourceType="Unspecified" />
    ///     </handlers>
    ///   </system.webServer>
    /// </configuration>
    /// 
    /// If IIS6 is being used, add the handler declaration under <system.web> instead.
    /// </example>
    public class WsgiHandler : IHttpHandler, IRequiresSessionState
    {
        public bool IsReusable
        {
            get { return false; }
        }

        public void ProcessRequest(HttpContext context)
        {
            if(wsgi == null)
            {
                if(config == null)
                    Interlocked.CompareExchange(ref config, WsgiSection.Load(), null);
                
                Wsgi newWsgi = new Wsgi(config);
                newWsgi.LoadAssembly(typeof(System.Web.HttpContext).Assembly);

                Interlocked.CompareExchange(ref wsgi, newWsgi, null);
            }

            wsgi.Run(new WsgiAspNetContext(context, config));
        }

        private static IWsgiConfig config;
        private static Wsgi wsgi;
    }
}
